import Vue from 'vue'
import Vuex from 'vuex'
import socket from '@/socket/index'

Vue.use(Vuex)

const state = {
  nickname: '',
  nicknames: [],
  holder: '',
  lines: [],
  connected: false,
  isGame: false
}

const mutations = {
  getNickname(state, nickName) {
    state.nickname = nickName
  },
  upDataNickName(state, nickNames) {
    state.nicknames = nickNames || []
  },
  upDateHolder(state, holder) {
    state.holder = holder
  },
  upDateLines(state, lines) {
    state.lines = lines || []
  },
  addToName(state, contxt) {
    if (!state.nicknames.includes(contxt)) {
      state.nicknames.push(contxt)
    }
  },
  upDateconnection(state, filg) {
    state.connected = filg
  },
  upDateconnections(state, filg) {
    state.isGame = filg
  },
  addToHolder(state, filg) {
    state.holder = filg
  },
  // 画新线
  drawNewLine(state, newLine) {
    state.lines.push(newLine)
  },

  // 鼠标滑动，更新线
  updateNewLine(state, lastLine) {
    // 更新vuex中最后一项的points即可
    const line = state.lines[state.lines.length - 1]
    line.points = lastLine.points
  }
}

const actions = {
  getName(context, intext) {
    return new Promise((res, rej) => {
      socket.emit('check_user_exist', intext, isExist => {
        res(isExist)
      })
    })
  },
  setName(context) {
    const nickName = localStorage.getItem('token')
    socket.emit('enter', nickName)
    context.commit('getNickname', nickName)
  },
  sendstope(state, filg) {
    socket.emit('start_game', filg)
  },
  sendplay() {
    socket.emit('stop_game')
  },
  daan(state, val) {
    socket.emit('answer_game', val)
  },
  sendDrawNewLine(context, line) {
    socket.emit('new_line', line)
  },
  sendUpdateNewLine(context, line) {
    socket.emit('update_line', line)
  }
}

const getters = {
  isGameState(state) {
    return !!state.holder
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
